﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using org.apache.zookeeper.data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using static org.apache.zookeeper.ZooDefs;

namespace Coldairarrow.Business.Interface
{
    public class DD_PushInterfaceBusiness : DDInterface_BaseBusiness, IJob_Business, ITransientDependency
    {

        //接口信息
        public Base_InterfaceOption DD_Push;
        //推送的钉钉的数据
        List<DD_ReqDTO_Push> pushDatas { get; set; } = new List<DD_ReqDTO_Push>();
        //创建成功返回的ID号
        public List<ReqProcessDTO> ProcessIDList { get; set; } = new List<ReqProcessDTO>();
        public DD_PushInterfaceBusiness()
        {
            this.InterfaceName = "钉钉通用推送";
            //索引字段
            this.MapFields = GetMapField("DD_Push");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            DD_Push = this.interfaceOption.Where(x => x.OperateType == "DD_Push").First();




            //查询执行前的事件
            //this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            ////查询执行中的事件
            //this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            ////查询执行中的事件
            //this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求前的事件
            this.BeforeNoQueryEvent += DD_PushProcessInterfaceBusiness_BeforeNoQueryEvent;
            //执行非查询请求中的事件
            this.OnNoQueryEvent += DD_PushProcessInterfaceBusiness_OnNoQueryEvent;
            //执行非查询请求后的事件
            this.AfterNoQueryEvent += DD_PushProcessInterfaceBusiness_AfterNoQueryEvent; ;
        }


        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void DD_PushProcessInterfaceBusiness_BeforeNoQueryEvent(object sender, DD_NoQueryEventArgs noQueryEventArgs)
        {
            //获取appId
            var key = JObject.Parse(DD_Push.TargetLoginData);
            noQueryEventArgs.UrlQuery.AppKey = key["appkey"].Value<string>();
            noQueryEventArgs.UrlQuery.AppSecret = key["appsecret"].Value<string>();
            noQueryEventArgs.UrlQuery.Corpid = key["corpid"].Value<string>();
            noQueryEventArgs.UrlQuery.Corpsecret = key["corpsecret"].Value<string>();
            //获取token
            JObject token = JObject.Parse(GetToken(noQueryEventArgs.UrlQuery));
            noQueryEventArgs.UrlQuery.Token = token["access_token"].ToString();
        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void DD_PushProcessInterfaceBusiness_OnNoQueryEvent(object sender, DD_NoQueryEventArgs noQueryEventArgs)
        {
            if (!string.IsNullOrEmpty(noQueryEventArgs.UrlQuery.Token))
            {
                //获取拼接token的URL
                noQueryEventArgs.HttpClient.Url = $"{DD_Push.TargetUrl}?access_token={noQueryEventArgs.UrlQuery.Token}";
                var date = (DD_ReqDTO_Push)noQueryEventArgs.Data;
                //获取审批表单的ID
                date.process_code = noQueryEventArgs.APINodes.Where(x => x.TargetField == "process_code").First().SourceField;
                //noQueryEventArgs.reqData = GetJsonData(noQueryEventArgs.APINodes, noQueryEventArgs.ParentNode, noQueryEventArgs.Data);
                noQueryEventArgs.reqData = date.ToJson();
            }
        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void DD_PushProcessInterfaceBusiness_AfterNoQueryEvent(object sender, DD_NoQueryEventArgs noQueryEventArgs)
        {
            try
            {
                //将查询后的数据转换成对应格式的数据
                DD_ResDTO_Push result = (DD_ResDTO_Push)JsonConvert.DeserializeObject<DD_ResDTO_Push>(noQueryEventArgs.Result);
                if (result.errmsg == "ok")
                {
                    noQueryEventArgs.Success = true;
                    //noQueryEventArgs.Result = new List<object>() { result };
                    ProcessIDList.Add(new ReqProcessDTO() { process_instance_id = result.process_instance_id });
                    noQueryEventArgs.Page.Complete = true;
                }
                else
                {
                    noQueryEventArgs.Success = false;
                }
            }
            catch (Exception ex)
            {
                noQueryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async Task ExecuteInterface()
        {

            try
            {

                //获取人员信息
                List<DD_UserDTO.User> users = this.SqlDb.GetListBySql<DD_UserDTO.User>("SELECT * FROM SD_DD_User");

                //创建人
                var createrList = users.Where(x => x.name == "王旺");
                List<string> creaters = new List<string>();
                if (!createrList.IsNullOrEmpty() && createrList.Count() > 0)
                {
                    creaters = createrList.Select(x => x.userid).ToList();
                }
                else
                {
                    creaters.Add("");
                }


                DD_ReqDTO_Push oreder = new DD_ReqDTO_Push();

                //表头信息
                List<string> userID = new List<string>();
                userID.Add("012626185729943055");
                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "申请人",
                    value = userID.ToJson()
                });
                oreder.originator_user_id = "012626185729943055";
                oreder.dept_id = 916115474;

                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "紧急程度",
                    value = "常规"
                });

                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "预计流程完成时间",
                    value = "2025-07-25"
                });

                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "选择审批线路",
                    value = "法歌帝审批线路"
                });

                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "是否需要实际支付",
                    value = "是"
                });

                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "付款单位",
                    value = "法歌帝生活科技（广东）有限公司(91442000MA54RA8A7B)"
                });

                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "费用类别",
                    value = "IT产品服务"
                });

                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "收款单位类型",
                    value = "供应商（物料类）"
                });

                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "搜索",
                    value = "合硕"
                });

                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "收款单位名称",
                    value = "中山市合硕高品电器有限公司"
                });

                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "其它收款单位名称",
                    value = "中山市合硕高品电器有限公司"
                });

                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "是否有签订合同协议",
                    value = "是"
                });
                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "币别",
                    value = "人民币"
                });

                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "发票状态",
                    value = "已提供发票"
                });
                oreder.form_component_values.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "是否异常费用",
                    value = "是"
                });




                //明细
                DD_ReqDTO_Push.Component details = new DD_ReqDTO_Push.Component();
                details.name = "请款明细(法歌帝线路)";

                List<List<DD_ReqDTO_Push.Component>> table = new List<List<DD_ReqDTO_Push.Component>>();
                //foreach (var item2 in item1)
                //{
                //每一行数据
                List<DD_ReqDTO_Push.Component> row = new List<DD_ReqDTO_Push.Component>();

                row.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "请款摘要",
                    value = "测试"
                });
                row.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "请款金额",
                    value = "123"
                });
                row.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "费用项目",
                    value = "其他"
                });
                row.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "费用所属部门",
                    value = "产品一部"
                });
                row.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "产品系列",
                    value = "公共."
                });
                row.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "销售方式",
                    value = "公共"
                });
                row.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "费用所属店铺",
                    value = "公共"
                });
                row.Add(new DD_ReqDTO_Push.Component()
                {
                    name = "结算方式",
                    value = "电汇"
                });
                table.Add(row);
                //}
                details.value = table;
                oreder.form_component_values.Add(details);
                pushDatas.Add(oreder);

                //发起钉钉审批
                await this.ExecuteNoQuery<DD_ReqDTO_Push>(pushDatas, this.DD_Push, this.SqlDb);

                //发起成功后获取钉钉单据
                if (ProcessIDList.Count > 0)
                {
                    DD_ProcessInterfaceBusiness query = new DD_ProcessInterfaceBusiness();
                    foreach (var item1 in ProcessIDList)
                    {
                        item1.process_instance_id = item1.process_instance_id;
                        //获取已发起成功的审批单号
                        var p = await query.QueryProcess(item1);

                    }

                }

            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 接口发送请求获取TOKEN
        /// </summary>
        /// <param name="ol_key"></param>
        /// <returns></returns>
        public string GetToken(DD_UrlQuery query)
        {
            //1.获取Token
            HttpClient httpClient = new HttpClient();
            httpClient.Method = "GET";
            // 设置请求参数
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat($"https://oapi.dingtalk.com/gettoken?");
            sb.AppendFormat($"appkey={query.AppKey}&");
            sb.AppendFormat($"appsecret={query.AppSecret}&");
            sb.AppendFormat($"corpid={query.Corpid}&");
            sb.AppendFormat($"corpsecret={query.Corpsecret}");
            httpClient.Url = sb.ToString();
            string sysReportResul1t = httpClient.Request();
            if (!sysReportResul1t.IsNullOrEmpty())
            {
                return sysReportResul1t;

            }
            else
            {
                return "";

            }
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
